package com.jinyi.wwdeng.autodialer.ui

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import androidx.core.graphics.toColorInt
import com.jinyi.wwdeng.autodialer.R
import com.jinyi.wwdeng.autodialer.databinding.ActivityLoginBinding
import com.jinyi.wwdeng.autodialer.http.HttpApi
import com.jinyi.wwdeng.autodialer.http.HttpCallback
import com.jinyi.wwdeng.autodialer.http.HttpUtil
import com.jinyi.wwdeng.autodialer.utils.AppConfig
import com.jinyi.wwdeng.autodialer.utils.TitleBarUtil
import org.json.JSONObject

/**
 * 登录
 */
class LoginAct: BaseAct(){
    private var binding: ActivityLoginBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        TitleBarUtil.setStatusBarColor(this,"#FFFFFFFF".toColorInt())
        TitleBarUtil.setStatusBarLightMode(this,true)

        // TODO: 测试默认填入账号
        binding?.etLoginName?.setText("SYSDH001")
        binding?.etPassword?.setText("Sysdh@001")

        binding?.btnLogin?.setOnClickListener {
            if (getLoginName().isEmpty()){
                showToast(getString(R.string.check_name))
                return@setOnClickListener
            }
            if (getLoginPassword().isEmpty()){
                showToast(getString(R.string.check_password))
                return@setOnClickListener
            }
            requestLoginAction()
        }

        // 检查是否已登录
        if (AppConfig.userToken.isNotEmpty()) {
            showLoginSuccess()
        }
    }

    private fun getLoginName(): String{
        return binding?.etLoginName?.text.toString()
    }

    private fun getLoginPassword(): String{
        return binding?.etPassword?.text.toString()
    }

    /**
     * 登录失败提示
     */
    private fun showLoginFailureDialog(){
        AlertDialog.Builder(this)
            .setTitle(getString(R.string.tips))
            .setMessage(getString(R.string.login_error))
            .setPositiveButton(getString(R.string.btn_retry)) { dialog, which ->
                requestLoginAction()
            }
            .setNegativeButton(getString(R.string.btn_cancel), null)
            .show()
    }

    /**
     * 登录成功
     */
    private fun showLoginSuccess(){
        val intent = Intent(this, MainActV2::class.java)
        startActivity(intent)
        finish()
    }

    /**
     * 登录
     */
    private fun requestLoginAction(){
        showLoading()
        val body = JSONObject().apply {
            put("loginName",getLoginName())
            put("passWord",getLoginPassword())
        }
        post(HttpApi.API_LOGIN, body,null,object : HttpCallback{
            override fun onSuccess(data: JSONObject) {
                val dataObj = data.optJSONObject("obj")
                dataObj?.let {
                    val userId = dataObj.optString("userId")
                    val userName = dataObj.optString("userName")
                    val token = dataObj.optString("token")

                    AppConfig.userId = userId
                    AppConfig.userName = userName
                    AppConfig.userToken = token
                    showLoginSuccess()
                }
            }
            override fun onFailure(error: String) {
                showLoginFailureDialog()
            }
            override fun onFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpUtil.getInstance().cancelRequests(this)
    }
}